//
//  UILabel+Extension.m
//  Weibo11
//
//  Created by JYJ on 15/12/5.
//  Copyright © 2015年 itheima. All rights reserved.
//

#import "UILabel+Extension.h"
#import <CoreText/CoreText.h>
@implementation UILabel (Extension)

+ (instancetype)labelWithTitle:(NSString *)title color:(UIColor *)color fontSize:(CGFloat)fontSize {
    return [self labelWithTitle:title color:color fontSize:fontSize alignment:NSTextAlignmentCenter];
}

+ (instancetype)labelWithTitle:(NSString *)title color:(UIColor *)color fontSize:(CGFloat)fontSize alignment:(NSTextAlignment)alignment {
    
    UILabel *lab = [[UILabel alloc] init];
    
    lab.text = title;
    lab.textColor = color;
    lab.font = [UIFont systemFontOfSize:fontSize];
    lab.numberOfLines = 0;
    lab.textAlignment = alignment;
    [lab sizeToFit];
    
    return lab;
}

+ (instancetype)labelWithTitle:(NSString *)title color:(UIColor *)color font:(UIFont *)font {
    return [self labelWithTitle:title color:color font:font alignment:NSTextAlignmentCenter];
}

+ (instancetype)labelWithTitle:(NSString *)title color:(UIColor *)color font:(UIFont *)font alignment:(NSTextAlignment)alignment {
    
    UILabel *lab = [[UILabel alloc] init];
    lab.text = title;
    lab.textColor = color;
    lab.font = font;
    lab.numberOfLines = 0;
    lab.textAlignment = alignment;
    [lab sizeToFit];
    return lab;
}


#pragma mark - 修改行间距
- (void)xhq_lineSpace:(CGFloat)lineSpace {
    
    [self xhq_lineSpace:lineSpace wordSpace:0 paragraphSpace:0];
}


#pragma mark - 修改字间距
- (void)xhq_wordSpace:(CGFloat)wordSpace {
    
    [self xhq_lineSpace:0 wordSpace:wordSpace paragraphSpace:0];
}


#pragma mark - 修改段间距
- (void)xhq_paragraphSpace:(CGFloat)paragraphSpace {
    
    [self xhq_lineSpace:0 wordSpace:0 paragraphSpace:paragraphSpace];
}


#pragma mark - 修改行间距，字体间距，段落间距
- (void)xhq_lineSpace:(CGFloat)lineSpace wordSpace:(CGFloat)wordSpace paragraphSpace:(CGFloat)paragraphSpace {
    
    NSString *string = self.text;
    
    NSMutableAttributedString *attributedString = nil;
    if (self.attributedText) {
        attributedString = [self.attributedText mutableCopy];
    }else {
        attributedString = [[NSMutableAttributedString alloc]initWithString:string];
    }
    
    if (wordSpace > 0) {
        [attributedString addAttributes:@{NSKernAttributeName:@(wordSpace)} range:NSMakeRange(0, [string length])];
    }
    
    if (lineSpace > 0) {
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineSpacing:lineSpace];
        [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [string length])];
    }
    
    if (paragraphSpace > 0) {
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setParagraphSpacing:paragraphSpace];
        [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [string length])];
    }
    
    self.attributedText = attributedString;
    [self sizeToFit];
}

-(void)textAlignmentLeftAndRight{
    [self textAlignmentLeftAndRightWith:CGRectGetWidth(self.frame)];
}

- (void)textAlignmentLeftAndRightWith:(CGFloat)labelWidth{
    if(self.text==nil||self.text.length==0) {
        return;
    }
    CGSize size = [self.text boundingRectWithSize:CGSizeMake(labelWidth,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:self.font} context:nil].size;
    NSInteger length = (self.text.length-1);
    NSString* lastStr = [self.text substringWithRange:NSMakeRange(self.text.length-1,1)];
    if([lastStr isEqualToString:@":"]||[lastStr isEqualToString:@"："]) {
        length = (self.text.length-2);
    }
    CGFloat margin = (labelWidth - size.width)/length;
    NSNumber*number = [NSNumber numberWithFloat:margin];
    NSMutableAttributedString* attribute = [[NSMutableAttributedString alloc]initWithString:self.text];
    [attribute addAttribute:NSKernAttributeName value:number range:NSMakeRange(0,length)];
    self.attributedText= attribute;
}
- (void)setReadMoreLabelContentMode:(CGFloat)labelWidth isMore:(BOOL)isMore{
    NSArray *contents = [self getLinesArrayOfLabelRows:labelWidth];
    if (contents.count <= 6) {
        self.userInteractionEnabled = NO; // 如果一行就不显示查看更多，同时取消手势响应
        return;
    }
    self.userInteractionEnabled=YES;
    
   //一个中文也算1个长度，如果末尾要截取的是英文，则“查看更多”会显示不全，所以截取的长度要长一些
    NSUInteger cutLength = 8; // 后面截取的长度
    
    NSMutableString *contentText = [[NSMutableString alloc] init];
    NSInteger countpp = isMore ? 6 : contents.count;
    for (NSInteger i = 0; i < countpp; i++) {
        if (i ==  countpp-1) { // 最后一行 进行处理加上.....
            
            NSString *lastLineText = [NSString stringWithFormat:@"%@",contents[i]];
            if (isMore) {
                NSUInteger lineLength = lastLineText.length;
                if (lineLength > cutLength) {
                    lastLineText = [lastLineText substringToIndex:(lastLineText.length - cutLength)];
                }
                [contentText appendString:[NSString stringWithFormat:@"%@",lastLineText]];
            }else{
                [contentText appendString:lastLineText];
            }
            
        } else {
            [contentText appendString:contents[i]];
        }
    }
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    NSDictionary *dictionary = @{
                                 NSForegroundColorAttributeName : self.textColor,
                                 NSFontAttributeName : self.font,
                                 NSParagraphStyleAttributeName : style
                                 };
    NSMutableAttributedString *mutableAttribText = nil;
    if (isMore) {
        mutableAttribText = [[NSMutableAttributedString alloc] initWithString:[contentText stringByAppendingString: @"\n全文"] attributes:dictionary];
    }else{
        mutableAttribText = [[NSMutableAttributedString alloc] initWithString:[contentText stringByAppendingString:@"\n收起"] attributes:dictionary];
    }
    [mutableAttribText addAttributes:@{
        NSFontAttributeName : [UIFont systemFontOfSize:AUTO(15)],
                                       NSForegroundColorAttributeName :[UIColor colorWithHue:0.61 saturation:0.53 brightness:0.54 alpha:1]
    } range:NSMakeRange(contentText.length, 3)];
    self.attributedText = mutableAttribText;
}

// 获取 Label 每行内容 得到一个数组
- (NSArray *)getLinesArrayOfLabelRows:(CGFloat)labelWidth{
    //CGFloat labelWidth = self.frame.size.width;
    //如果使用autolayout，labelWidth会为0
    
    NSString *text = [self text];
    UIFont *font = [self font];
    if (text == nil) {
        return nil;
    }
    CTFontRef myFont = CTFontCreateWithName(( CFStringRef)([font fontName]), [font pointSize], NULL);
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    [attStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attStr.length)];
    [attStr addAttribute:(NSString *)kCTFontAttributeName
                   value:(__bridge  id)myFont
                   range:NSMakeRange(0, attStr.length)];
    CFRelease(myFont);
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(( CFAttributedStringRef)attStr);
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(0,0,labelWidth,100000));
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
    NSArray *lines = ( NSArray *)CTFrameGetLines(frame);
    NSMutableArray *linesArray = [[NSMutableArray alloc]init];
    for (id line in lines) {
        CTLineRef lineRef = (__bridge  CTLineRef )line;
        CFRange lineRange = CTLineGetStringRange(lineRef);
        NSRange range = NSMakeRange(lineRange.location, lineRange.length);
        NSString *lineString = [text substringWithRange:range];
        CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr,
                                       lineRange,
                                       kCTKernAttributeName,
                                       (CFTypeRef)([NSNumber numberWithFloat:0.0]));
        CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr,
                                       lineRange,
                                       kCTKernAttributeName,
                                       (CFTypeRef)([NSNumber numberWithInt:0.0]));
        [linesArray addObject:lineString];
    }
    CGPathRelease(path);
    CFRelease(frame);
    CFRelease(frameSetter);
    return (NSArray *)linesArray;
}
@end
